package com.example.mobile2021606159yhf0521;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.DownloadManager;
import android.os.Bundle;
import android.telecom.Call;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.security.auth.callback.Callback;

public class MainActivity extends AppCompatActivity {
    private RecyclerView rvMainNews;
    String url="http://192.168.29.230:3000/news";
    //2.定义OKHttpClient客户端网络访问对象
    OkHttpClient okHttpClient = new OkHeepClient();
     Gson gson=new Gson();
     Type type=new TypeToken<List<News>>(){}.getType();
     List<News> newsList=new ArrayList<>();
     NewsRVAdapter newsRVAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initVIew();
        rvMainNews.setLayoutManager(new LinearLayoutManager(this));
        //1.定义访问路径字符串和子线程和使用子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //3.在子线程的run（）方法中。定义网络访问请求
                Request request=new Request.Builder()
                        .url(url)
                        .build();
                //根据网络请求request，由OKHTTPClient客户端创建请求执行对象call
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback(){
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e){

                    }
                    @Override
                    public void onResponse(@NonNull Call call,@NonNull Response response) throws IOException {
                        String result=response.body().string();
                        newsList=gson.fromJson(result, type);
                        Log.i("TAG","onResponse:"+newsList.size());
                        newsRVAdapter=new NewsRVAdapter(newsList);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rvMainNews.setAdapter(newsRVAdapter);
                            }
                        });

                    }
                });


            }
        }).start();
    }
    private void initVIew(){
        rvMainNews = (RecyclerView) findViewById(R.id.rvMainNews);
    }
}